from sqlalchemy import Column, Integer, String, Float, ForeignKey, Boolean, DateTime, Text, JSON
from sqlalchemy.orm import relationship
from datetime import datetime
from commons.database import Base


class Order(Base):
    """订单表模型，存储订单基本信息"""
    __tablename__ = "orders"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="订单ID")
    buyer_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment="买家ID")
    seller_id = Column(Integer, ForeignKey('users.id'), nullable=False, comment="卖家ID")
    status = Column(Integer, default=0, comment="订单状态：0-待付款，1-已付款，2-已发货，3-已完成，4-已取消")
    total_amount = Column(Float, nullable=False, comment="订单总金额")
    payment_proof = Column(JSON, comment="付款凭证图片路径列表")
    logistics_info = Column(Text, comment="物流信息")
    contact_info = Column(String(200), comment="联系方式")
    created_at = Column(DateTime, default=datetime.utcnow, comment="创建时间")
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment="更新时间")

    # 定义关系
    buyer = relationship("User", foreign_keys=[buyer_id], backref="buyer_orders")
    seller = relationship("User", foreign_keys=[seller_id], backref="seller_orders")
    items = relationship("OrderItem", backref="order", cascade="all, delete-orphan")

    def to_dict(self):
        """将订单对象转换为字典"""
        return {
            "id": self.id,
            "buyer_id": self.buyer_id,
            "seller_id": self.seller_id,
            "status": self.status,
            "total_amount": self.total_amount,
            "payment_proof": self.payment_proof,
            "logistics_info": self.logistics_info,
            "contact_info": self.contact_info,
            "created_at": self.created_at.strftime("%Y-%m-%d %H:%M:%S") if self.created_at else None,
            "updated_at": self.updated_at.strftime("%Y-%m-%d %H:%M:%S") if self.updated_at else None,
            "items": [item.to_dict() for item in self.items]
        }


class OrderItem(Base):
    """订单项表模型，存储订单中的商品信息"""
    __tablename__ = "order_items"

    id = Column(Integer, primary_key=True, autoincrement=True, comment="订单项ID")
    order_id = Column(Integer, ForeignKey('orders.id'), nullable=False, comment="订单ID")
    product_id = Column(Integer, ForeignKey('products.id'), nullable=False, comment="产品ID")
    quantity = Column(Integer, nullable=False, comment="商品数量")
    price = Column(Float, nullable=False, comment="购买时的单价")

    # 定义关系
    product = relationship("Product", back_populates="orders")

    def to_dict(self):
        """将订单项对象转换为字典"""
        return {
            "id": self.id,
            "order_id": self.order_id,
            "product_id": self.product_id,
            "quantity": self.quantity,
            "price": self.price,
            "product_name": self.product.name if self.product else None,
            "product_image": self.product.cover_image if self.product else None
        }